const { defineConfig } = require('@vue/cli-service')
const path = require('path')

module.exports = defineConfig({
  transpileDependencies: true,
  
  // 基础路径
  publicPath: process.env.NODE_ENV === 'production' ? './' : '/',
  
  // 输出目录
  outputDir: process.env.OUTPUT_DIR,
  
  // 静态资源目录
  assetsDir: 'static',
  
  // 生产环境是否生成 sourceMap 文件
  productionSourceMap: false,
  
  // 开发服务器配置
  devServer: {
    host: '0.0.0.0',
    port: 8080,
    open: true,
    hot: true,
    compress: true,
    historyApiFallback: true,
    allowedHosts: 'all',
    client: {
      overlay: {
        warnings: false,
        errors: true
      },
      // 确保WebSocket连接使用localhost而不是内网IP
      webSocketURL: {
        hostname: 'localhost',
        port: 8080,
        protocol: 'ws'
      }
    },
    // 代理配置 - 仅开发环境使用
    proxy: {
      '/wujue_cs_test': {
        target: 'http://localhost:9681',
        changeOrigin: true,
        secure: false,
        logLevel: 'debug',
        pathRewrite: {
          '^/wujue_cs_test': '/wujue_cs_test'
        }
      },
      '/wujue_cs': {
        target: 'http://localhost:9681',
        changeOrigin: true,
        secure: false,
        logLevel: 'debug',
        pathRewrite: {
          '^/wujue_cs': '/wujue_cs'
        }
      }
    }
  },
  
  // 配置别名
  configureWebpack: {
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src'),
        'components': path.resolve(__dirname, 'components'),
        'pages': path.resolve(__dirname, 'pages'),
        'static': path.resolve(__dirname, 'static'),
        'utils': path.resolve(__dirname, 'utils')
      }
    },
    // 性能优化
    optimization: {
      splitChunks: {
        chunks: 'all',
        cacheGroups: {
          vendor: {
            name: 'vendor',
            test: /[\\/]node_modules[\\/]/,
            priority: 10,
            chunks: 'initial'
          },
          common: {
            name: 'common',
            minChunks: 2,
            priority: 5,
            chunks: 'initial',
            reuseExistingChunk: true
          }
        }
      }
    }
  },
  
  // CSS 相关配置
  css: {
    extract: process.env.NODE_ENV === 'production',
    sourceMap: false,
    loaderOptions: {
      scss: {
        additionalData: `@import "@/styles/variables.scss";`
      }
    }
  },
  
  // 链式操作配置
  chainWebpack: config => {
    // 移除 preload 插件
    config.plugins.delete('preload')
    config.plugins.delete('prefetch')
    
    // 注释掉图片压缩配置，因为image-webpack-loader依赖安装失败
    // config.module
    //   .rule('images')
    //   .use('image-webpack-loader')
    //   .loader('image-webpack-loader')
    //   .options({
    //     mozjpeg: { progressive: true, quality: 65 },
    //     optipng: { enabled: false },
    //     pngquant: { quality: [0.65, 0.90], speed: 4 },
    //     gifsicle: { interlaced: false },
    //     webp: { quality: 75 }
    //   })
    
    // 生产环境配置
    if (process.env.NODE_ENV === 'production') {
      // 移除 console
      config.optimization.minimizer('terser').tap(args => {
        args[0].terserOptions.compress.drop_console = true
        args[0].terserOptions.compress.drop_debugger = true
        return args
      })
    }
  },
  
  // 第三方插件配置
  pluginOptions: {
    // uni-app 配置
    'uni-app': {
      // H5 配置
      h5: {
        title: '武绝传说',
        template: path.resolve(__dirname, 'public/index.html'),
        router: {
          mode: 'hash',
          base: './'
        },
        async: {
          loading: 'AsyncLoading',
          timeout: 20000
        },
        // 资源加载配置
        resourcesLoad: {
          // 启用资源预加载
          preload: true,
          // 预加载资源类型
          preloadAssets: ['js', 'css', 'images'],
          // 加载完成回调
          onComplete: 'window.dispatchEvent(new CustomEvent("resourcesLoaded"))'
        },
        // 优化配置
        optimization: {
          treeShaking: {
            enable: true
          },
          // 预加载规则
          preloadRule: {
            packages: ['pages', 'components'],
            // 预加载登录页面
            include: [
              'pages/login/index.vue',
              'pages/main/index.vue'
            ]
          },
          // 代码分割
          splitChunks: {
            pages: {
              name: 'pages',
              chunks: 'all',
              minChunks: 1,
              priority: 10
            }
          }
        },
        // 全局样式
        globalStyle: {
          navigationBarTextStyle: 'white',
          navigationBarTitleText: '武绝传说',
          navigationBarBackgroundColor: '#1e3c72',
          backgroundColor: '#f5f5f5'
        }
      }
    }
  }
})